package org.litespring.beans.factory.support;

import org.litespring.beans.BeanDefinition;

/**
 * @author ChangLiang
 * @date 2020/8/31
 */
public class BeanDefinitonReaderUtils {

    /**
     * Separator for generated bean names. If a class name or parent name is not
     * unique, "#1", "#2" etc will be appended, until the name becomes unique.
     */
    public static final String GENERATED_BEAN_NAME_SEPARATOR = "#";

    public static String registerWithGeneratedNames(GenericBeanDefinition definition, BeanDefinitionRegistry registry) {
        String generatedName = generateBeanName(definition, registry, false);
        registry.registerBeanDefinition(generatedName, definition);
        return generatedName;
    }

    public static String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean) {
        String generatedBeanName = definition.getBeanClassName();
        String id = generatedBeanName;
        if (isInnerBean) {
            // Inner bean: generate identity hashcode suffix
            id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + Integer.toHexString(System.identityHashCode(definition));
        } else {
            // Top-level bean: use plain class name
            // Increase counter until the id is unique
            int counter = -1;
            while (counter == -1 || registry.getBeanDefinition(id) != null) {
                counter++;
                id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + counter;
            }
        }
        return id;
    }
}
